<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form
      ref="dictLayEntryFormRef"
      :model="form"
      label-width="120px"
      :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('dictLayEntry.dictCode')" prop="dictCode">
            <el-input
              v-model="form.dictCode"
              :placeholder="$t('dictLayEntry.dictCodeRequired')"
              maxlength="30"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('dictLayEntry.dictName')" prop="dictName">
            <el-input
              v-model="form.dictName"
              :placeholder="$t('dictLayEntry.dictNameRequired')"
              maxlength="120"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('dictLayEntry.typeCode')" prop="typeCode">
            <jmash-select
              v-model="form.typeCode"
              :placeholder="$t('dictEntry.typeCode')"
              :data="Dict.layoutDictType.values"
              disabled
              class="w-full"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('dictLayEntry.parentId')" prop="parentId">
            <el-tree-select
              v-model="form.parentId"
              :data="layEntryBizLayDict.values"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="styleWidth"
              :placeholder="$t('dictLayEntry.parentIdRequired')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('dictLayEntry.enable')" prop="enable">
            <el-switch v-model="form.enable" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item
            :label="$t('dictLayEntry.description')"
            prop="description"
          >
            <el-input
              v-model="form.description"
              :placeholder="$t('dictLayEntry.descriptionRequired')"
              maxlength="120"
              show-word-limit
              clearable
              :rows="3"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import type { PropType } from "vue";

import { ref, reactive, toRef } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

import type {
  DictLayEntryKey,
  DictLayEntryFormReq,
  DictLayEntryCreateReq,
  DictLayEntryUpdateReq,
} from "@/api/dict/os-dict-lay-entry/types";
import { dictLayEntryApi } from "@/api/dict/os-dict-lay-entry/index";
import { Dict } from "@/api/dict/dict";
import { EntryIdBizLayDict } from "@/api/dict/index";
//加载业务数据.
Dict.layoutDictType.useValues();

const dictLayEntryFormRef = ref<FormInstance>();

let form: DictLayEntryFormReq = reactive<DictLayEntryFormReq>({
  requestId: Math.random() * 10 + "",
  updateMask: "enable,parentId,dictName,description",
  enable: true,
});

const rules = reactive<FormRules<DictLayEntryFormReq>>({
  typeCode: [
    {
      required: true,
      message: t("dictLayEntry.typeCode"),
      trigger: "change",
    },
  ],
  dictCode: [
    {
      required: true,
      message: t("dictLayEntry.dictCodeRequired"),
      trigger: "blur",
    },
  ],
  dictName: [
    {
      required: true,
      message: t("dictLayEntry.dictNameRequired"),
      trigger: "blur",
    },
  ],
});

const model = defineModel<boolean>();

const props = defineProps({
  entityKey: {
    type: Object as PropType<DictLayEntryKey>,
    default: () => {},
  },
  typeCode: {
    type: String,
  },
  parentId: {
    type: String,
  },
});

form.typeCode = props.typeCode;
form.parentId = props.parentId;
//层级字典
let layEntryBizLayDict = new EntryIdBizLayDict({
  typeCode: form.typeCode,
  excludeId: props.entityKey.dictId,
});
layEntryBizLayDict.useValues();

const emits = defineEmits(["refresh"]);

const keys = Object.keys(props.entityKey);

const update = ref(keys.length >= 1);

if (update.value) {
  dictLayEntryApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
  });
}
// 提交表单校验
const submitForm = async () => {
  await dictLayEntryFormRef.value?.validate((valid) => {
    if (valid) {
      if (update.value) {
        dictLayEntryApi
          .update(form as DictLayEntryUpdateReq)
          .then((response) => {
            console.log(response);
            if (response.status === 200) {
              ElMessage({
                message: t("common.submitSuccess"),
                type: "success",
              });
              if (model.value) {
                model.value = false;
              }
              emits("refresh", response.status === 200);
            }
          });
      } else {
        dictLayEntryApi
          .create(form as DictLayEntryCreateReq)
          .then((response) => {
            console.log(response);
            if (response.status === 200) {
              ElMessage({
                message: t("common.submitSuccess"),
                type: "success",
              });
              if (model.value) {
                model.value = false;
              }
              emits("refresh", response.status === 200);
            }
          });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
<style scoped lang="scss">
.w-full {
  width: 100% !important;
}
</style>
